Skip to main content

Closure and Lexical Scope

Closure

A closure is a combination of functions inside a main function. Closure is created when child function keeps the environment of the parent scope even after the parent function has already executed. Closure gives you access to an outer functions scope from an inner function.

function testFn() {
function innerFn(a) {
// innerFn() is a closure
return a;
}
return innerFn;
}
var result = testFn();
console.log(result(2));

Function innerFn() is a closure inside testFn() function. To invoke the closure first outer function has to be invoked by assigning var result = testFn(). Then to call closure add a parentheses to result() which will invoke the closure as shown.

Lexical Scope

A lexical scope means a variable defined outside a function is accessible from inside of the function. But opposite condition is not possible.

var a = 5; // variable a assigned to 10

function outerFn() {
// outermost function
var b = 4;
console.log("a and b is accessible in outer:", a, b);
function innerFn() {
// innermost function
var c = 3;
console.log("a and b and c is accessible in innner:", a, b, c);
}

return innerFn();
}
outerFn(); // invoke function func
console.log("only a is accessible in global:", a);